<template>
  <div class="home-container">
    <!-- 欢迎卡片 -->
    <div class="welcome-card animate__animated animate__fadeInUp">
      <h1>{{ welcomeMessage }}</h1>
      <p>欢迎使用云服务管理系统，祝您使用愉快！</p>
    </div>

    <!-- 系统概览 -->
    <div class="overview-section">
      <h2 class="section-title">系统概览</h2>
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in overviewData" :key="index">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-icon" :style="{ backgroundColor: item.color }">
              <el-icon :size="24"><component :is="item.icon" /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ item.value }}</div>
              <div class="stat-label">{{ item.label }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 告警信息 -->
    <div class="activity-section">
      <h2 class="section-title">告警信息
        <el-tag size="small" v-if="alarms.length > 0" :type="hasCriticalAlarms ? 'danger' : 'warning'">
          {{ activeAlarmCount }}条活跃告警
        </el-tag>
      </h2>
      <el-empty v-if="alarms.length === 0" description="暂无告警信息" :image-size="100" />
      <el-timeline v-else>
        <el-timeline-item
          v-for="(alarm, index) in alarms"
          :key="index"
          :timestamp="formatTime(alarm.timestamp)"
          :color="alarm.color"
          placement="top"
        >
          <el-card 
            class="alarm-card" 
            shadow="hover"
            :style="{ 'border-left-color': alarm.color }"
          >
            <h4>
              <el-tag :type="alarm.severity === 'high' ? 'danger' : 'warning'" size="small">
                {{ alarm.type }}
              </el-tag>
            </h4>
            <p>{{ alarm.content }}</p>
            <div class="node-info">节点: {{ alarm.node }}</div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <h2 class="section-title">快速操作</h2>
      <el-row :gutter="20">
        <el-col :span="6" v-for="(action, index) in quickActions" :key="index">
          <el-card shadow="hover" class="action-card" @click="handleAction(action)">
            <div class="action-icon">
              <el-icon :size="32"><component :is="action.icon" /></el-icon>
            </div>
            <div class="action-title">{{ action.title }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { 
  User, 
  Monitor, 
  DataLine, 
  Plus, 
  Refresh, 
  SwitchButton, 
  Connection 
} from '@element-plus/icons-vue'

const router = useRouter()

// 欢迎消息
const user = JSON.parse(localStorage.getItem('code_user') || '{}')
const welcomeMessage = computed(() => {
  return user?.name ? `${user.name}，您好！` : '您好！'
})

// 概览数据
const overviewData = ref([])

// 告警信息
const alarms = ref([])

// 快速操作
const quickActions = ref([
  { icon: Plus, title: '创建虚拟机', route: '/manager/vm' },
  { icon: Refresh, title: '刷新状态', action: 'refresh' },
  { icon: SwitchButton, title: '启动/停止', route: '/manager/vm' },
  { icon: Connection, title: '虚拟机迁移', route: '/manager/vm' }
])

// 增强的时间格式化函数
const formatTime = (timestamp) => {
  if (!timestamp) return '未知时间'
  const date = new Date(timestamp * 1000)
  return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
}

// 获取概览数据
const fetchOverviewData = async () => {
  try {
    const [vmsRes, nodesRes, usersRes] = await Promise.all([
      request.get('/api/vms'),
      request.get('/api/nodes'),
      request.get('/api/users')
    ])
    
    const vms = vmsRes.data.items
    const nodes = nodesRes.data.items
    const users = usersRes.data.items
    
    const runningVMs = vms.filter(vm => vm.status === 'running').length
    const stoppedVMs = vms.filter(vm => vm.status === 'stopped').length
    const totalCpuUsage = nodes.reduce((sum, node) => sum + (node.cpuUsage || 0), 0) / (nodes.length || 1)
    const activeUsers = users.filter(user => user.status === 'ACTIVE').length
    
    overviewData.value = [
      { icon: Monitor, label: '运行中虚拟机', value: runningVMs, color: '#67C23A' },
      { icon: SwitchButton, label: '已停止虚拟机', value: stoppedVMs, color: '#F56C6C' },
      { icon: DataLine, label: '总CPU使用率', value: `${Math.round(totalCpuUsage)}%`, color: '#409EFF' },
      { icon: User, label: '活跃用户', value: activeUsers, color: '#E6A23C' }
    ]
  } catch (error) {
    console.error('获取概览数据失败:', error)
    ElMessage.error('获取概览数据失败，请稍后重试')
    overviewData.value = [
      { icon: Monitor, label: '运行中虚拟机', value: 0, color: '#67C23A' },
      { icon: SwitchButton, label: '已停止虚拟机', value: 0, color: '#F56C6C' },
      { icon: DataLine, label: '总CPU使用率', value: '0%', color: '#409EFF' },
      { icon: User, label: '活跃用户', value: 0, color: '#E6A23C' }
    ]
  }
}

// 获取告警信息
const fetchAlarms = async () => {
  try {
    const { data } = await request.get('/api/alarms')
    alarms.value = data.items.slice(0, 4).map(alarm => ({
      timestamp: alarm.timestamp,
      type: alarm.type || '未分类告警',
      content: alarm.content || '无详细描述',
      node: alarm.node || '未知节点',
      color: alarm.status === 'processed' ? '#0BBF87' : '#F56C6C',
      severity: alarm.severity || 'medium'
    }))
  } catch (error) {
    console.error('获取告警信息失败:', error)
    alarms.value = [
      {
        timestamp: Math.floor(Date.now() / 1000),
        type: '系统错误',
        content: '无法获取告警信息',
        node: '管理系统',
        color: '#F56C6C',
        severity: 'high'
      }
    ]
    ElMessage.error('获取告警信息失败，请稍后重试')
  }
}

// 计算活跃告警数量
const activeAlarmCount = computed(() => {
  return alarms.value.filter(a => a.color !== '#0BBF87').length
})

// 检查是否有严重告警
const hasCriticalAlarms = computed(() => {
  return alarms.value.some(a => a.severity === 'high' && a.color !== '#0BBF87')
})

// 处理快速操作
const handleAction = (action) => {
  if (action.route) {
    router.push(action.route)
  } else if (action.action === 'refresh') {
    ElMessage.success('数据已刷新')
    fetchOverviewData()
    fetchAlarms()
  }
}

// 初始化数据
onMounted(() => {
  fetchOverviewData()
  fetchAlarms()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-card {
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.welcome-card h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.welcome-card p {
  font-size: 16px;
  color: #606266;
}

.section-title {
  font-size: 20px;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  height: 100%;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.activity-section {
  margin: 30px 0;
}

.action-card {
  text-align: center;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.action-icon {
  margin-bottom: 15px;
  color: #409EFF;
}

.action-title {
  font-size: 16px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .welcome-card {
    padding: 20px;
  }
  
  .welcome-card h1 {
    font-size: 24px;
  }
  
  .el-col {
    margin-bottom: 15px;
  }
}
/* 样式部分 */
.alarm-card {
  border-left: 3px solid; /* 颜色通过内联样式动态设置 */
  transition: all 0.3s;
}

.alarm-card:hover {
  transform: translateX(3px);
}

.alarm-card h4 {
  margin-bottom: 8px;
  font-size: 16px;
  color: #303133;
}

.alarm-card p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 0;
}

.alarm-card .node-info {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>